package com.nx.platform.es.bean.modle.param;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Table;
import com.nx.platform.es.common.utils.MoreSplitters;
import com.nx.platform.es.bean.dto.RequestContext;
import com.nx.platform.es.biz.wrapper.parser.StatementOperator;
import com.nx.platform.es.common.utils.MoreMaps;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.elasticsearch.common.Strings;

import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.nx.platform.es.biz.wrapper.parser.StatementOperator.EQUAL;

/**
 * @author
 * @since 2016年10月15日
 */
public class SltrKeywordsHandler implements ParamFieldHandler {

    private static final Pattern WORD_NUMBER_CHINESE = Pattern.compile("[^.a-zA-Z0-9\\u4e00-\\u9fa5-]+");

    @Override
    public void handle(RequestContext context, ImmutableMap<String, ?> fieldConfig,
                       Table<String, StatementOperator, List<String>> queryTable,
                       Table<String, StatementOperator, List<String>> paramsTable, Map<String, Object> paramsMap) {
        String fieldFace = MapUtils.getString(fieldConfig, "face");
        if (Strings.isNullOrEmpty(fieldFace)) {
            return;
        }
        List<String> refers = MoreMaps.getObject(fieldConfig, "refers");
        if (CollectionUtils.isEmpty(refers)) {
            return;
        }
        String query = refers.stream().flatMap(refer -> {
            List<String> fieldValues = queryTable.get(refer, EQUAL);
            if (CollectionUtils.isEmpty(fieldValues)) {
                return Stream.empty();
            }
            String fieldValue = fieldValues.get(0);
            if (Strings.isNullOrEmpty(fieldValue)) {
                return Stream.empty();
            }
            return MoreSplitters.VERTICAL.splitAsStream(fieldValue).map(s -> WORD_NUMBER_CHINESE.matcher(s).replaceAll(" ").toLowerCase().trim());
        }).map(s -> "(" + s + ")").collect(Collectors.joining(" OR "));
        if (!query.isEmpty()) {
            context.getTrace().append("&_param_").append(fieldFace).append(EQUAL.getSymbol()).append(query);
            paramsMap.put(fieldFace, query);
        }

    }

}
